package com.sihan.framework.etm.common.websocket;

import java.net.URI;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import com.sihan.framework.etm.service.SessionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;

import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;



/**
 *
 *websocket 连接拦截器
 * @author 苏伟洪
 * @date  2023/03/08 17:10:24
 *
 */
@Configuration
@Slf4j
public class WebSocketInterceptor extends HttpSessionHandshakeInterceptor {

    @Autowired
    private SessionService sessionService;

    /*
     * 握手后
     * websocket连接时指定了Sec-WebSocket-Protocol,后端接收到连接后，必须原封不动的将SecWebSocket-Protocol头信息返回给前端，否则连接会抛出异常
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {

    }

    /*
     * 握手前
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                                   Map<String, Object> attributes) {
        String sessionId = request.getHeaders().getFirst("sec-Websocket-protocol");
        HttpHeaders headers = response.getHeaders();
        headers.add("sec-Websocket-protocol",sessionId);
        if (!"".equals(sessionId)) {
            //检查是否存在
            if (sessionService.isExpires(sessionId)) {
                response.setStatusCode(HttpStatus.OK);
                attributes.put("sessionId", sessionId);
                return true;
            }
            //session过期拦截
            log.info("session已过期:{}",sessionId);
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return false;
        }
        log.info("WebSocket拦截器：session为空");
        response.setStatusCode(HttpStatus.FORBIDDEN);

        return false;
    }

    @Override
    public Collection<String> getAttributeNames() {
        // TODO Auto-generated method stub
        return super.getAttributeNames();
    }

    @Override
    public boolean isCopyAllAttributes() {
        // TODO Auto-generated method stub
        return super.isCopyAllAttributes();
    }

    @Override
    public void setCopyAllAttributes(boolean copyAllAttributes) {
        // TODO Auto-generated method stub
        super.setCopyAllAttributes(copyAllAttributes);
    }

    @Override
    public boolean isCopyHttpSessionId() {
        // TODO Auto-generated method stub
        return super.isCopyHttpSessionId();
    }

    @Override
    public void setCopyHttpSessionId(boolean copyHttpSessionId) {
        // TODO Auto-generated method stub
        super.setCopyHttpSessionId(copyHttpSessionId);
    }

    @Override
    public boolean isCreateSession() {
        // TODO Auto-generated method stub
        return super.isCreateSession();
    }

    @Override
    public void setCreateSession(boolean createSession) {
        // TODO Auto-generated method stub
        super.setCreateSession(createSession);
    }

    /**
     * 从 cookie中取出 session
     *
     * @param cookie cookie
     * @return session
     */
    public String getSession(String cookie) {
        String[] split = cookie.split(";");
        for (String s : split) {
            String[] split1 = s.split("=");
            if ("JSESSIONID".equals(split1[0].trim())) {
                return split1[1].trim();
            }
        }
        return "";
    }

}
